<template>
  <div class="app-container">
    <FilterSearch :value="queryParams" :config="configData" layout="inline"></FilterSearch>
    <main>
      <div class="table">
        <a-table :scroll="{ x: 1400 }" bordered :dataSource="tableData.dataSource" :columns="tableData.columns"
          :pagination="false" :loading="tableData.loading">
          <template #bodyCell="{ column, index, record }">
            <template v-if="column.key === 'action'">
              <a-button type="link" @click="handleChange(record, 'details')">
                详情
              </a-button>
              <a-button type="link" @click="handleChange(record, 'inHome')">
                入库
              </a-button>
            </template>
            <template v-if="column.key === 'index'">
              <span>
                {{ (index + 1) }}
              </span>
            </template>
            <template v-if="column.key === 'serviceType'">
              <template v-for="item in typeOptions.options1">
                <span v-if="record.serviceType == item.codeValue" style="text-align:center;" color="#f50">{{
                  item.codeName }}</span>
              </template>
            </template>
            <template v-if="column.key === 'serviceMode'">
              <template v-for="item in typeOptions.options2">
                <span v-if="record.serviceMode == item.codeValue" color="#f50">{{ item.codeName }}</span>
              </template>
            </template>
          </template>
        </a-table>
      </div>
      <div class="page">
        <a-pagination v-model:current="queryParams.pageNumber" :show-total="total => ` 总条数:${total}条`"
          v-model:pageSize="queryParams.pageSize" :total="tableData.total" @change="currentChange" />
      </div>
    </main>

    <a-modal v-model:open="modalOpen.open1" style="width: 75%" title="档案详细信息" :maskClosable="false" :closable="false">
      <div class="modal-body">
        <div class="form">
          <a-form disabled :model="formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
            <a-row>
              <a-col :span="8">
                <a-form-item label="合同号" name="contractNum">
                  <a-input v-model:value="formState.contractNum" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="身份证号" name="idCard">
                  <a-input v-model:value="formState.idCard" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="业务模式" name="serviceMode">
                  <a-select allowClear v-model:value="formState.serviceMode">
                    <a-select-option v-for="(item, index) in typeOptions.options2" :value="item.codeValue"
                      :key="item.codeValue">
                      {{ item.codeName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="承租人" name="lesseeName">
                  <a-input v-model:value="formState.lesseeName" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="业务类型" name="serviceType">
                  <a-select allowClear v-model:value="formState.serviceType">
                    <a-select-option v-for="(item, index) in typeOptions.options1" :value="item.codeValue"
                      :key="item.codeValue">
                      {{ item.codeName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="入池时间" name="enterPoolTime">
                  <a-input v-model:value="formState.enterPoolTime" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="车架号" name="carNum">
                  <a-input v-model:value="formState.carNum" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="渠道描述" name="channelDesc">
                  <a-input v-model:value="formState.channelDesc" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="车牌号" name="licensePlateNum">
                  <a-input v-model:value="formState.licensePlateNum" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="二网经销商" name="secondDealer">
                  <a-input v-model:value="formState.secondDealer" />
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item :label-col="{ span: 2 }" :wrapper-col="{ span: 22 }" label="备注" name="remark">
                  <a-textarea v-model:value="formState.remark" :auto-size="{ minRows: 3, maxRows: 3 }" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </div>
      <template #footer>
        <div class="modal-btns">
          <div class="modal-btn">
            <a-button @click="cancel('details')">关闭</a-button>
          </div>
        </div>
      </template>
    </a-modal>

    <a-modal v-model:open="modalOpen.open2" style="width: 50%" title="档案操作记录" :maskClosable="false" :closable="false">
      <div class="modal-body">
        <div class="table">
          <a-table bordered :dataSource="tableData.modalDataSource" :columns="tableData.modalColumns" :pagination="{ total: tableData.modalDataSource.length, showTotal: total => ` 总条数:${total}条` }">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'eventNode'">
                <template v-for="item in typeOptions.options3">
                  <span v-if="record.eventNode == item.codeValue" style="text-align:center;" color="#f50">{{
                    item.codeName }}</span>
                </template>
              </template>
            </template>
          </a-table>
        </div>
      </div>
      <template #footer>
        <div class="modal-btns">
          <div class="modal-btn">
            <a-button @click="cancel('record')">关闭</a-button>
          </div>
        </div>
      </template>
    </a-modal>

    <a-modal v-model:open="modalOpen.open3" title="入库" style="width:500px;" :maskClosable="false" :closable="false">
      <div class="modal-body">
        <div class="form">
          <a-form :rules="rules" :model="inHomeForm" ref="formRef" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }"
            autocomplete="off">
            <a-row>
              <a-col :span="24">
                <a-form-item label="档案存储地" name="fileLocation">
                  <a-input v-model:value="inHomeForm.fileLocation" />
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="备注" name="remark">
                  <a-textarea v-model:value="inHomeForm.remark" :auto-size="{ minRows: 3, maxRows: 3 }" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </div>
      <template #footer>
        <div class="modal-btns">
          <div class="modal-btn">
            <a-button @click="handleChange({}, 'submit')" type="primary">确认</a-button>
          </div>
          <div class="modal-btn">
            <a-button @click="cancel('inHome')">关闭</a-button>
          </div>
        </div>
      </template>
    </a-modal>

    <a-modal v-model:open="modalOpen.open4" title="批量入库" :maskClosable="false" :closable="false">
      <div class="modal-body">
        <div class="form">
          {{ uploadErr.tips }}
        </div>
      </div>
      <template #footer>
        <div class="modal-btns">
          <div class="modal-btn" v-if="uploadErr.data.length > 0">
            <a-button type="primary" @click="handleChange({}, 'downloadErr')">下载</a-button>
          </div>
          <div class="modal-btn">
            <a-button @click="cancel('downloadErr')">关闭</a-button>
          </div>
        </div>
      </template>
    </a-modal>

    <div class="shade" v-show="spin">
      <a-spin size="large" />
    </div>
  </div>
</template>
<script setup lang="ts">
import { computed, ref, reactive } from "vue";
import {
  getList, getRows, downloadTable, importExcel, importExcelErr,
  filesOperationRecord, inHome
} from "@/api/retailStored";
import { downloadTemplate, getQueryAll } from "@/api/common";
import { downloadFile, formatDate } from "@/utils/index";
import { message } from 'ant-design-vue';
import { MATERIAL } from '@/utils/config';

const spin = ref(false);
const formRef = ref({});
const queryParams = ref({
  pageNumber: 1,
  pageSize: 10,
  startTimeAndEndTime: [formatDate(new Date() - (1000 * 60 * 60 * 24 * 6)), formatDate(new Date())],
  startTime: '',
  endTime: '',
});
const modalOpen = reactive({
  open1: false,
  open2: false,
  open3: false,
  open4: false
});
const typeOptions = reactive({
  options1: [],
  options2: [],
  options3: []
})
const uploadErr = reactive({
  tips: "",
  data: []
})
const tableData = reactive({
  dataSource: [],
  columns: [
    {
      title: "序号",
      dataIndex: "index",
      key: "index",
      width: 80,
      align: "center",
    },
    {
      title: "合同号",
      dataIndex: "contractNum",
      key: "contractNum",
    },
    {
      title: "承租人",
      dataIndex: "lesseeName",
      key: "lesseeName",
    },
    {
      title: "业务类型",
      dataIndex: "serviceType",
      key: "serviceType",
      width: 90,
      align: "center",
    },
    {
      title: "渠道描述",
      dataIndex: "channelDesc",
      key: "channelDesc",
    },
    {
      title: "业务模式",
      dataIndex: "serviceMode",
      key: "serviceMode",
      width: 90,
      align: "center",
    },
    {
      title: "入池时间",
      dataIndex: "enterPoolTime",
      key: "enterPoolTime",
      width: 160,
      align: "center",
      sorter: {
        compare: (a: any, b: any) => a.enterPoolTime > b.enterPoolTime
      }
    },
    {
      title: "操作",
      key: "action",
      width: 160,
      fixed: "right",
    },
  ],
  modalDataSource: [],
  modalColumns: [
    {
      title: "节点名称",
      dataIndex: "eventNode",
      key: "eventNode",
      width: 120
    },
    {
      title: "操作时间",
      dataIndex: "createdTime",
      key: "createdTime",
      width: 160,
      align: "center",
    },
    {
      title: "操作人",
      dataIndex: "createdBy",
      key: "createdBy",
    },
    {
      title: "备注",
      dataIndex: "remark",
      key: "remark",
    }
  ],
  loading: false,
  total: 0,
});
interface FormState {
  [props: string]: string | number | Array<object> | Array<string>;
}
let formState: FormState = reactive({
});
let inHomeForm: FormState = reactive({
  id: "",
  fileLocation: "",
  remark: ""
});
const configData = computed(() => {
  let config = {
    itemConfig: [
      {
        type: "input",
        prop: "lesseeName",
        allowClear: "关闭",
        label: "承租人",
        placeholder: "请输入",
      },
      {
        type: "input",
        prop: "contractNum",
        allowClear: "关闭",
        label: "合同号",
        placeholder: "请输入",
      },
      {
        type: "input",
        prop: "carNum",
        allowClear: "关闭",
        label: "车架号",
        placeholder: "请输入",
      },
      {
        type: "input",
        prop: "licensePlateNum",
        allowClear: "关闭",
        label: "车牌号",
        placeholder: "请输入",
      },
      {
        type: "input",
        prop: "idCard",
        allowClear: "关闭",
        label: "身份证号",
        placeholder: "请输入",
      },
      {
        type: "dateRange",
        valueFormat: "YYYY-MM-DD",
        prop: "startTimeAndEndTime",
        allowClear: "关闭",
        label: "入池时间",
        placeholder: ["请选择", "请选择"]
      },
    ],
    operate: [
      {
        icon: "",
        type: "primary",
        name: "查询",
        handleClick: getLoad,
        rule: true,
      },
      {
        icon: "",
        type: "primary",
        name: "重置",
        handleClick: reset,
        rule: true,
      },
      {
        icon: "",
        type: "primary",
        name: "导出",
        handleClick: exportData,
        rule: true,
      },
      {
        icon: "",
        type: "primary",
        name: "下载模板",
        handleClick: download,
        rule: true,
      },
      {
        icon: "",
        type: "primary",
        name: "批量入库",
        handleClick: batchHome,
        rule: true,
      },
    ],
    rules: {},
  };
  return config;
});
const rules = computed(() => {
  let rules = {
    fileLocation: [{ required: true, message: "请输入", trigger: "blur" }],
  };
  return rules;
});

function getLoad() {
  if (queryParams.value.startTimeAndEndTime != null && queryParams.value.startTimeAndEndTime.length > 0) {
    queryParams.value.startTime = queryParams.value.startTimeAndEndTime[0] + ' 00:00:00';
    queryParams.value.endTime = queryParams.value.startTimeAndEndTime[1] + ' 23:59:59';
  } else {
    queryParams.value.startTime = '';
    queryParams.value.endTime = '';
  }
  tableData.loading = true;
  getList({ ...queryParams.value, basicDataVo: { ...queryParams.value, state: MATERIAL.WAREHOUSE }, dataSource: MATERIAL.RETAIL }).then((res: any) => {
    if ((queryParams.value.pageNumber * queryParams.value.pageSize) > res.total && res.total > 0 && queryParams.value.pageNumber > 1) {
      queryParams.value.pageNumber = 1;
      getLoad();
    } else {
      tableData.dataSource = res.records;
      tableData.total = res.total;
      tableData.loading = false;
    }
  });
}
function reset() {
  queryParams.value = {
    pageNumber: 1,
    pageSize: 10,
    startTimeAndEndTime: [],
    startTime: null,
    endTime: null,
  };
  getLoad();
}
function exportData() {
  spin.value = true;
  if (queryParams.value.startTimeAndEndTime != null && queryParams.value.startTimeAndEndTime.length > 0) {
    queryParams.value.startTime = queryParams.value.startTimeAndEndTime[0] + ' 00:00:00';
    queryParams.value.endTime = queryParams.value.startTimeAndEndTime[1] + ' 23:59:59';
  } else {
    queryParams.value.startTime = '';
    queryParams.value.endTime = '';
  }
  downloadTable({ ...queryParams.value, dataSource: MATERIAL.RETAIL, excelType: MATERIAL.RETAILHOUSEEXPORTTYPE, basicDataVo: { ...queryParams.value, state: MATERIAL.WAREHOUSE } }).then((res: any) => {
    if (res) {
      downloadFile(res, "待入库.xlsx");
    };
    spin.value = false;
  });
}
function download() {
  spin.value = true;
  downloadTemplate({ type: 'waitLib' }).then((res: any) => {
    if (res) {
      downloadFile(res, "批量入库模板.xlsx");
    };
    spin.value = false;
  });
}
function batchHome() {
  let upload = document.createElement("input");
  upload.type = "file";
  upload.addEventListener("change", (e: any) => {
    if (e.target.files.length <= 0) return;
    let file = e.target.files[0];
    let formData = new FormData();
    formData.append("file", file);
    formData.append("importExcelType", MATERIAL.RETAILHOUSEEXPORTTYPE);
    formData.append("dataSource", MATERIAL.RETAIL);
    spin.value = true;
    importExcel(formData).then((res: any) => {
      if (res) {
        message.success('文件上传成功');
        getLoad();
        for (const key in res) {
          uploadErr.tips = key;
          uploadErr.data = res[key];
        }
        modalOpen.open4 = true;
      }
      spin.value = false;
    })
  });
  upload.click();
}
function currentChange(pageNumber: number, pageSize: number) {
  queryParams.value.pageNumber = pageNumber;
  queryParams.value.pageSize = pageSize;
  pageLoad();
}
function handleChange(row: any = {}, type: string) {
  switch (type) {
    case "details":
      spin.value = true;
      getRows({ basicDataVo: { id: row.id, state: MATERIAL.WAREHOUSE }, dataSource: MATERIAL.RETAIL }).then((res: any) => {
        if (res) {
          formState = Object.assign(formState, res.materialBasicDataDto);
          modalOpen.open1 = true;
        }
        spin.value = false;
      });
      break;
    case "record":
      spin.value = true;
      filesOperationRecord({ archivesNum: row.archivesNum }).then((res: any) => {
        tableData.modalDataSource = res;
        modalOpen.open2 = true;
        spin.value = false;
      })
      break;
    case "inHome":
      inHomeForm.id = row.id;
      modalOpen.open3 = true;
      break;
    case "submit":
      inHome({ dataSource: MATERIAL.RETAIL, basicDataVo: { ...inHomeForm, state: MATERIAL.WAREHOUSE } }).then((res: any) => {
        if (res) {
          message.success("入库成功");
        }
        cancel('inHome');
        getLoad();
      })
      break;
    case "downloadErr":
      spin.value = true;
      importExcelErr(uploadErr.data).then((res: any) => {
        downloadFile(res, "批量入库失败数据.xlsx");
        spin.value = false;
      })
      break;
    default:
      break;
  }
}
function cancel(type: string) {
  switch (type) {
    case "details":
      modalOpen.open1 = false;
      for (const key in formState) {
        delete formState[key];
      }
      break;
    case 'record':
      modalOpen.open2 = false;
      tableData.modalDataSource = [];
      break;
    case "inHome":
      modalOpen.open3 = false;
      for (const key in inHomeForm) {
        delete inHomeForm[key];
      }
      break;
    case "downloadErr":
      modalOpen.open4 = false;
      uploadErr.tips = "";
      uploadErr.data = [];
      break;
    default:
      break;
  }
}
function getOptionsList() {
  getQueryAll({ codeType: 'serviceType' }).then((res: any) => {
    typeOptions.options1 = res;
  });
  getQueryAll({ codeType: 'serviceMode' }).then((res: any) => {
    typeOptions.options2 = res;
  });
  getQueryAll({ codeType: 'eventType' }).then((res: any) => {
    typeOptions.options3 = res;
  });
}
getLoad();
getOptionsList();
</script>
<style lang="less" scoped></style>
